using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin2022Soft1.Application.Common.Interface;
using Admin2022Soft1.Application.RequestDto;
using Admin2022Soft1.Application.ResponseDto;
using Admin2022Soft1.Domain.Entity;
using Admin2022Soft1.Infrastructure.Utils;
using Microsoft.AspNetCore.Mvc;

namespace Admin2022Soft1.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IIdentityService _identityService;
        private readonly IRepository<AppUser> _appUser;

        public UsersController(IIdentityService identityService, IRepository<AppUser> appUser)
        {
            _identityService = identityService;
            _appUser = appUser;
        }

        [HttpPost]
        [Route("token")]
        public async Task<string> ValideUser(UserForAuthDto userForAuthDto)
        {
            if (!_identityService.ValidateUserAsync(userForAuthDto))
            {
                return new { Code = 4000, Msg = "用户名或者密码不正确，请确认后重试！" }.SerializeObject();
            }

            var token = await _identityService.GenerateTokenAsync();

            var res = new
            {
                Code = 1000,
                Data = token,
                Msg = "登录成功"
            };

            return res.SerializeObject();
        }

        [HttpPost]
        [Route("refreshtoken")]
        public async Task<IActionResult> RefreshToken(AppTokenDto appTokenDto)
        {
            var tokenToReturn = await _identityService.RefreshTokenAsync(appTokenDto);
            return Ok(tokenToReturn);
        }

        [HttpGet]
        public dynamic Get([FromQuery] QueryWithPager query)
        {//get请求默认从uri从获取参数，所以此处应该加上FromQuery的特性才能正确获得参数
            var pageIndex = query.Pager.PageIndex;
            var pageSize = query.Pager.PageSize;
            var keyword = string.IsNullOrEmpty(query.Keyword) ? "" : query.Keyword.Trim();

            // 获得所有满足条件的记录
            var users = _appUser.Table.Where(x => x.IsDeleted == false);

            // 如果存在关键字，则对用户名进行查询，此处只是一个演示，可以根据实际情况对昵称、角色名等进行模糊查询
            if (!string.IsNullOrEmpty(keyword))
            {
                users = users.Where(x => x.Username.Contains(keyword));
            }

            // 对获得的记录分页
            var u = users.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取用户列表成功^_^"
            };
            return res;
        }

        [HttpGet("{id}")]
        public async Task<dynamic> Get(Guid id)
        {
            var user = await _appUser.GetByIdAsync(id);

            if (user == null)
            {
                return new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "指定用户不存在"
                };

            }
            return new
            {
                Code = 1000,
                Data = user,
                Msg = "获取用户列表成功^_^"
            };

        }

        [HttpPost]
        public async Task<string> Post(CreateAppUserDto model)
        {
            var username = model.Username.Trim();
            var nickname = model.Nickname?.Trim();
            var avatarId = model.Avatar;
            var password = model.Password.Trim();
            var remarks = model.Remarks?.Trim();

            if (string.IsNullOrEmpty(username))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "用户名不能为空，请确认后重试"
                };
                return tmp.SerializeObject();
            }

            var user = new AppUser
            {
                Username = username,
                Password = "113",
                Nickname = nickname,
                Avatar = avatarId,
                Remarks = remarks
            };

            await _appUser.AddAsync(user);

            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功"
            };
            return res.SerializeObject();
        }

        [HttpPut("{id}")]
        public async Task<dynamic> Put(Guid id, CreateAppUserDto model)
        {
            var user = await _appUser.GetByIdAsync(id);

            if (user != null)
            {
                user.Username = model.Username;
                // user.Password = model.Password;
                user.Nickname = model.Nickname;
                user.Avatar = model.Avatar;
                user.Remarks = model.Remarks;
                await _appUser.UpdateAsync(user);
                return JsonHelper.SerializeObject(new
                {
                    Code = 1000,
                    Data = user,
                    Msg = string.Format("你修改的用户的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.SerializeObject(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }

        [HttpDelete("{id}")]
        public async Task<dynamic> Delete(Guid id)
        {
            var user = await _appUser.GetByIdAsync(id);
            if (user != null)
            {
                if (user.IsDeleted)
                {
                    return new
                    {
                        Code = 104,
                        Msg = string.Format("该用户已经删除！", id)
                    }.SerializeObject();
                }
                await _appUser.UpdateAsync(user);
                return new
                {
                    Code = 1000,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                }.SerializeObject();
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                }.SerializeObject();
            }

        }
    }
}